package org.feng.navigation.domain.rpc.tianxing.domainservice;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.feng.navigation.common.util.StringUtil;
import org.feng.navigation.common.util.TimeUtil;
import org.feng.navigation.domain.rpc.tianxing.domainobject.allnews.TianXingAllNewsRequest;
import org.feng.navigation.domain.rpc.tianxing.domainobject.allnews.TianXingAllNewsResponse;
import org.feng.navigation.domain.rpc.tianxing.gateway.TianXingHttpClient;
import org.feng.navigation.domain.tianxing.entity.TianXingAllNewsObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 天行数据接口服务实现
 *
 * @version v1.0
 * @author: junzi
 * @date: 2023年02月05日 13时45分
 */
@Slf4j
@Service
public class TianXingApiServiceImpl implements TianXingApiService {

    @Resource
    private TianXingHttpClient tianXingHttpClient;

    @Override
    public void tianXingAllNews(TianXingAllNewsObject tianXingAllNewsObject) {

        TianXingAllNewsRequest request = new TianXingAllNewsRequest();
        // 设置新闻数量
        request.setNum(tianXingAllNewsObject.getNewsCount());
        // 设置新闻频道
        request.setCol(tianXingAllNewsObject.getTianXingAllNewsTypeEnum().getChannelId());

        // 请求天行新闻接口
        TianXingAllNewsResponse response = tianXingHttpClient.execute(request);
        // 响应失败
        if (!response.isSuccess()) {
            tianXingAllNewsObject.setErrorMessage(response.getMsg());
            return;
        }
        // 处理响应
        TianXingAllNewsResponse.TianXingAllNewsResponseData result = response.getResult();
        if (Objects.nonNull(result)) {
            List<TianXingAllNewsResponse.TianXingAllNewsResponseList> newsList = result.getNewsList();
            if (CollectionUtil.isNotEmpty(newsList)) {
                List<TianXingAllNewsObject.AllNewsData> allNewsDataList = new ArrayList<>();
                tianXingAllNewsObject.setNewsList(allNewsDataList);
                for (TianXingAllNewsResponse.TianXingAllNewsResponseList news : newsList) {
                    TianXingAllNewsObject.AllNewsData allNewsData = new TianXingAllNewsObject.AllNewsData();
                    allNewsDataList.add(allNewsData);
                    allNewsData.setUrl(news.getUrl());
                    allNewsData.setTitle(news.getTitle());
                    allNewsData.setPicUrl(news.getPicUrl());
                    allNewsData.setSource(news.getSource());
                    allNewsData.setDate(TimeUtil.parse(StringUtil.substring(news.getCtime(), 10)));
                }
            }
        }
    }
}
